package com.runda.biz.service;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.bbjob.mapper.ProductionMapper;
import com.bbjob.model.Production;
import com.bbjob.model.ProductionCodes;
import com.bbjob.util.service.impl.BaseService;
import com.runda.biz.dto.MutiCodesDto;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class ProductionCodesService extends BaseService<ProductionCodes> implements IProductCodeService {
    @Resource
    private ProductionMapper prodMapper;

    @Override
    public int save(MutiCodesDto code, Integer productId) {
        Production product = new Production();
        product.setId(productId);
        code.forEach((key, value) -> {
            code.generateCodeList(productId, key).forEach(productCode -> this.mapper.insert(productCode));
            String codes = code.get(key).stream().collect(Collectors.joining(","));
            try {
                BeanUtils.setProperty(product, key, codes);
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        });
        this.prodMapper.updateByPrimaryKeySelective(product);
        return 1;
    }
    @Override
    public int save(ProductionCodes entity) {
        this.mapper.insert(entity);
        ProductionCodes record = new ProductionCodes();
        record.setCodeType(entity.getCodeType());
        record.setProductId(entity.getProductId());
        List<ProductionCodes> list=this.selectByRecord(record);
        if(list.size()>0){
            String codes =list.stream().map(ProductionCodes::getCode).collect(Collectors.joining(","));
            Production prod=new Production();
            prod.setId(entity.getProductId());
            try {
                BeanUtils.setProperty(prod, entity.getCodeType(), codes);
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            this.prodMapper.updateByPrimaryKeySelective(prod);
        }
        return 1;
    }

} 